import {Alert, ToastAndroid} from "react-native";

type AlcoholMeasurement = {
    value: number;
    unit: string;
    rawData: string;
    timestamp: string;
    isTested: boolean;
};

class AlcoholParser {
    static readonly SERVICE_UUID: string = '0000FF00-0000-1000-8000-00805F9B34FB';
    static readonly DATA_CHARACTERISTIC: string = '0000FF01-0000-1000-8000-00805F9B34FB';
    static readonly COMMAND_CHARACTERISTIC: string = '0000FF02-0000-1000-8000-00805F9B34FB';

    // 开始测量命令
    static readonly START_COMMAND: string = 'bcfd07010000';
    // 取消测量命令
    static readonly STOP_COMMAND: string = '553600000000000000000000000001735532';

    static parseData(hexString: string): AlcoholMeasurement | null {
        // 移除空格并转换为大写
        const cleanHex = hexString.replace(/\s+/g, '').toUpperCase();
        if (cleanHex === 'BCFD0802030003') {
            ToastAndroid.show('吹气中断! 请再吹一次', ToastAndroid.SHORT);
        }
        if (cleanHex === 'BCFD0802000000') {
            ToastAndroid.show('请开始吹气', ToastAndroid.SHORT);
        }
        try {
            // 验证基础格式（11字节=22字符）
            if (cleanHex.length !== 22) return null;
            // 提取关键字段（第6-7字节，即索引10-13）
            const concentrationHex = cleanHex.substring(10, 14);
            // 大端序转换（高位在前）
            const decimalValue = parseInt(concentrationHex, 16);
            // 转换为mg/100mL（除以100）
            return {
                value: decimalValue / 100,
                unit: 'mg/100ml',
                rawData: hexString,
                timestamp: new Date().toISOString(),
                isTested: true  // 只有实际解析到数据才标记为已测试
            };
        } catch (e) {
            return null;
        }
    }

    // 创建一个未测试的测量结果
    static createUntestedResult(): AlcoholMeasurement {
        return {
            value: 0,
            unit: 'mg/100ml',
            rawData: '',
            timestamp: new Date().toISOString(),
            isTested: false
        };
    }
}

export default AlcoholParser;
export type {AlcoholMeasurement};
